﻿package com.wxsoft.business.sys.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wxsoft.business.model.easyui.PageHelper;
import com.wxsoft.business.sys.dao.ISysMenuDao;
import com.wxsoft.business.sys.pojo.SysMenu;
import com.wxsoft.business.sys.service.ISysMenuService;

@Service("sysMenuService")
public class SysMenuServiceImpl implements ISysMenuService  {
	@Resource
	private ISysMenuDao dao;
	
	
	public long findCount(SysMenu sysMenu) {
		return dao.findCount(sysMenu);
	}
	
	public List<SysMenu> findAll(PageHelper page,SysMenu sysMenu) {
        List<SysMenu> r = dao.findAll(page,sysMenu);
		return r;
	}
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public String add(SysMenu sysMenu) {

		SysMenu mForQ = new SysMenu();
		mForQ.setCode(sysMenu.getCode());
		List<SysMenu> sysMeunL =  dao.getMenuBy(mForQ);
		if(sysMeunL!=null && sysMeunL.size()>0){
			throw new RuntimeException("编号重复，请重新输入！"+sysMenu.getCode()+sysMenu.getName());
		}

		//获取菜单层级//获取菜单父类
		this.setMenuForAM(sysMenu);
		this.dao.insert(sysMenu);
		return "操作成功!";
	}
	
	public String modify(SysMenu sysMenu) {
		//获取菜单层级//获取菜单父类
		this.setMenuForAM(sysMenu);
		this.dao.modify(sysMenu);
		return "操作成功!";
	}
	
	
	
	public String delete(SysMenu sysMenu) {
		this.dao.delete(sysMenu);
		return "操作成功!";
	}
	/**
	 * 设置级别  和  父菜单 为 增加和修改
	 * @param sysMenu
	 */
	public void setMenuForAM(SysMenu sysMenu){

		if("0".equals(sysMenu.getPcode())){
			sysMenu.setLevels("1");
			sysMenu.setPcodes("[0],");
		}else{
			//获取父菜单
			SysMenu mForQ = new SysMenu();
			mForQ.setCode(sysMenu.getPcode());
			List<SysMenu> sysMenuL =  dao.getMenuBy(mForQ);
			if(sysMenuL!=null && sysMenuL.size()>0){
				for(SysMenu sysM : sysMenuL){
					//设置当前层级
					String levels = sysM.getLevels();
					int lev =  Integer.valueOf(levels).intValue()+1;
					sysMenu.setLevels(""+lev);
					//设置当前父菜单
					sysMenu.setPcodes(sysM.getPcodes()+"["+sysMenu.getPcode()+"],");
				}
			}else{
				throw new RuntimeException("未找到父菜单，请重新选择！");
			}
		}
		
	}

	/**
	 * 获取菜单byuserId
	 * @param userId
	 * @return
	 */
	public List<SysMenu> getMenuByUserId(String userId){
		List<SysMenu> menuList = this.dao.getMenuByUserId(userId);
		return menuList;
	}
	/**
	 * 获取该用户权限的菜单
	 * @param userId
	 * @return
	 */
	public List<SysMenu> getMenu(String userId) {
		return dao.getMenuByUserId(userId);  
	}
	/**
	 * 获取 菜单
	 * @param userId
	 * @return
	 */
	public List<SysMenu> getMenuBy(SysMenu sysMenu) {
		return dao.getMenuBy(sysMenu);  
	}

	@Override
	public List<SysMenu> getMenuByRole(String role_code) {
		return dao.getMenuByRole(role_code);  
	}
	
}
